package com.code.bolg.controller;

import com.code.bolg.bean.Article;
import com.code.bolg.bean.Comment;
import com.code.bolg.enums.DelFlagEnum;
import com.code.bolg.output.CommentOutPut;
import com.code.bolg.output.IndexDto;
import com.code.bolg.service.CommentService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Comment
 *
 * @author  2018-10-12
 */
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    /**
     * 新增或编辑
     */
    @PostMapping("/saveOrUpdate")
    public Object save(Comment comment) {
        if(comment.getId()!=null){
            comment.setUpdateDate(new Date());
        }else if(comment.getId()==null){
            comment.setCreatDate(new Date());
            comment.setUpdateDate(comment.getCreatDate());
            comment.setFlag(DelFlagEnum.NOTDELETE.getCode());
        }
        Comment save = commentService.save(comment);
        CommentOutPut outPut = new CommentOutPut();
        BeanUtils.copyProperties(save,outPut);
        return outPut;
    }

    /**
     * 删除
     */
    @GetMapping("/delete")
    public Object delete(int id) {
        return commentService.deleteById(id);
    }

    /**
     * 查询
     */
    @GetMapping("/find")
    public Object find(int id) {
        Comment comment = commentService.findById(id);
        return comment;
    }

    /**
     *  查询
     */
    @PostMapping("/list")
    public Object list(Comment model,
                       @RequestParam(required = false, defaultValue = "0") int page,
                       @RequestParam(required = false, defaultValue = "10") int size) {
        List<CommentOutPut> list = new ArrayList<>();
        Page<Comment> all = commentService.findAll(model, page - 1 == -1 ? 0 : page - 1, size);
        for (Comment c:all.getContent()){
            CommentOutPut ouput = new CommentOutPut();
            BeanUtils.copyProperties(c,ouput);
            list.add(ouput);
        }
        IndexDto<CommentOutPut> indexDto = new IndexDto<>();
        indexDto.setCount(Integer.valueOf (String.valueOf(all.getTotalElements())));
        indexDto.setList(list);
         return indexDto;
    }

}

